package com.ctw.mapmycity;

import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ctw.mapmycity.auth.LoginType;
import com.ctw.mapmycity.client.RequestMethod;
import com.ctw.mapmycity.client.RestClient;
import com.ctw.mapmycity.model.Account;
import com.google.gson.Gson;

public class RegisterActivity extends Activity {
	
	private TextView mFullName;
	private TextView mEmail;
	private TextView mPassword;
	
    private Button btnRegister;
    
    private TextView loginScreen; 
	private TextView textheaderregister;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set View to register.xml
        setContentView(R.layout.register);
        findViewById(R.id.registerRelativeLayout).requestFocus();
        
        loginScreen = (TextView) findViewById(R.id.link_to_login);

        textheaderregister = (TextView) findViewById(R.id.textheaderregister);
        textheaderregister.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/AgentOrange.ttf"));
        
		mFullName = (TextView) findViewById(R.id.reg_fullname);
		mEmail = (TextView) findViewById(R.id.reg_email);
		mPassword = (TextView) findViewById(R.id.reg_password);
		mPassword.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == event.KEYCODE_ENTER){
					doRegister();
				}
				return false;
			}
		});
						
        // Listening to Login Screen link
        loginScreen.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				// Switching to Login Screen/closing register screen
				finish();
			}
		});
        
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnRegister.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				doRegister();
			}
        });
    }
	
	private void doRegister() {
		
		if (! validateFields()) return;
		
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive())
			imm.hideSoftInputFromWindow(RegisterActivity.this.getCurrentFocus().getWindowToken(), 0);

		new AsyncTask<Account, Void, Account>() {
			@Override
			protected void onPreExecute() {
			}

			@Override
			protected Account doInBackground(Account... account) {
				Account acc = account[0];
				
				Gson gson = new Gson();
				try {
					RestClient client = null;
					client = new RestClient("/account");
					client.AddHeader("Accept", "application/json");
					client.AddHeader(HTTP.CONTENT_TYPE, "application/json");
					
					client.AddParam("account", gson.toJsonTree(acc).toString());
					client.Execute(RequestMethod.POST);
					String response = client.getResponse();
					
					acc = gson.fromJson(response, com.ctw.mapmycity.model.Account.class);

				} catch (Exception e) {
					acc = null;
				}
				
				return acc;
			}

			@Override
			protected void onPostExecute(final Account acc) {
				
				if (acc == null ) {
					// TODO ERROR MSG, based on 
					Toast.makeText(RegisterActivity.this,
							"Email já foi cadastrado!", 
							Toast.LENGTH_SHORT)
							.show();
					
				} else {
					
					Toast.makeText(RegisterActivity.this,
							"O cadastro foi realizado. Por favor, faça o login!", 
							Toast.LENGTH_SHORT)
							.show();
					
					// return to login screen with the credentials to just create the account
					finish();
				}
			}

			@Override
			protected void onCancelled() {
			}
			
		}.execute(new Account(mEmail.getText().toString(), mFullName.getText().toString(), mPassword.getText().toString(),  mPassword.getText().toString(), 
				LoginType.STANDARD.getType()));
		
	}

	private boolean validateFields() {
		boolean result = true;
		
		// Reset errors.
		mFullName.setError(null);
		mEmail.setError(null);
		mPassword.setError(null);

		View focusView = null;

		// Check for a full name password.
		if (TextUtils.isEmpty(mFullName.getText().toString().trim())) {
			mFullName.setError(getString(R.string.error_field_required));
			focusView = mFullName;
			result = false;
		} 
		
		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail.getText().toString().trim())) {
			mEmail.setError(getString(R.string.error_field_required));
			focusView = focusView != null ? focusView : mEmail;
			result = false;
			
		} else if (!mEmail.getText().toString().trim().contains("@")) {
			mEmail.setError(getString(R.string.error_invalid_email));
			focusView = focusView != null ? focusView : mEmail;
			result = false;
		}
		
		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword.getText().toString().trim())) {
			mPassword.setError(getString(R.string.error_field_required));
			focusView = focusView != null ? focusView : mPassword;
			result = false;
		} 
		
		if (! result) {
			focusView.requestFocus();
		}

		return result;
	}
}